package thinkinjava4.ch21_concurrency;


import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Accessor implements Runnable {
    private final int id;

    public Accessor(int idn) {
        id = idn;
    }

    @Override
    public void run() {
        //isInterrupted 方便终止线程
        while (!Thread.currentThread().isInterrupted()) {
            ThreadLocalVariableHolder.increment();
            System.out.println(this);
            Thread.yield();
        }
    }

    @Override
    public String toString() {
        return "Thread #" + id + ": " + ThreadLocalVariableHolder.get();
    }
}

/**
 * 线程本地存储
 */
public class ThreadLocalVariableHolder {
    //ThreadLocal通常当作静态域存储
    private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
        private Random random = new Random(47);

        @Override
        protected synchronized Integer initialValue() {
            return random.nextInt(10000);
        }
    };

    /**
     * increment()和get()不是synchronized 因为ThreadLocal保证不会出现竞争条件
     * 线程之间 每个线程有自己独立的存储空间，不会产生资源竞争
     */
    public static void increment() {
        value.set(value.get() + 1);
    }

    public static int get() {
        return value.get();
    }

    public static void main(String[] args) throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
            exec.execute(new Accessor(i));
        TimeUnit.MILLISECONDS.sleep(5);//Run for a while
        exec.shutdownNow();//All Accessors will quit
    }
}
